<template>
  <div class="research-review-center">
    <div class="page-header">
      <h1 class="page-title">科研项目审核中心</h1>
      <div class="header-actions">
        <el-button type="primary" @click="fetchProjects">刷新</el-button>
      </div>
    </div>

    <el-card>
      <div class="filter-bar">
        <el-select v-model="filterStatus" placeholder="审核状态" style="width: 140px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="申报中" value="申报中" />
          <el-option label="结题审核中" value="结题审核中" />
        </el-select>
        
        <el-select v-model="filterType" placeholder="项目类型" style="width: 140px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="纵向" value="纵向" />
          <el-option label="横向" value="横向" />
          <el-option label="校级" value="校级" />
        </el-select>

        <el-select v-model="filterLevel" placeholder="项目级别" style="width: 140px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="校级" value="校级" />
          <el-option label="市厅级" value="市厅级" />
          <el-option label="省部级" value="省部级" />
          <el-option label="国家级" value="国家级" />
        </el-select>
        
        <div class="filter-summary">
          <el-tag type="info" size="small">
            共 {{ projects.length }} 个科研项目待审核
          </el-tag>
          <el-button size="small" style="margin-left: 8px;" @click="clearFilters">清除筛选</el-button>
        </div>
      </div>

      <!-- 项目列表 -->
      <el-table :data="projects" v-loading="loading" stripe>
        <el-table-column prop="name" label="项目名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="projectNumber" label="项目编号" width="150" />
        <el-table-column prop="projectType" label="项目类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getProjectTypeTagType(row.projectType)" size="small">
              {{ row.projectType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="subjectCategory" label="学科分类" width="120" show-overflow-tooltip />
        <el-table-column prop="level" label="项目级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)" size="small">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sourceUnit" label="来源单位" width="150" show-overflow-tooltip />
        <el-table-column prop="totalFunding" label="经费总额" width="120">
          <template #default="{ row }">
            {{ row.totalFunding ? `${row.totalFunding}万元` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="当前状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="提交时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" style="color:#e6a23c;" @click="openReview(row)">审核</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog v-model="showReviewDialog" title="科研项目审核" width="600px">
      <div class="review-info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="项目名称">{{ reviewProject?.name }}</el-descriptions-item>
          <el-descriptions-item label="项目类型">
            <el-tag :type="getProjectTypeTagType(reviewProject?.projectType)" size="small">
              {{ reviewProject?.projectType || '-' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="学科分类">{{ reviewProject?.subjectCategory }}</el-descriptions-item>
          <el-descriptions-item label="项目级别">
            <el-tag :type="getLevelTagType(reviewProject?.level)" size="small">
              {{ reviewProject?.level || '-' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="来源单位">{{ reviewProject?.sourceUnit }}</el-descriptions-item>
          <el-descriptions-item label="经费总额">{{ reviewProject?.totalFunding ? `${reviewProject.totalFunding}万元` : '-' }}</el-descriptions-item>
          <el-descriptions-item label="当前状态">{{ reviewProject?.status }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <el-form :model="reviewForm" label-width="100px" style="margin-top: 20px;">
        <el-form-item label="审核结果" required>
          <el-radio-group v-model="reviewForm.status">
            <el-radio label="已通过">通过</el-radio>
            <el-radio label="已驳回">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" required>
          <el-input v-model="reviewForm.opinion" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReviewDialog = false">取消</el-button>
        <el-button type="primary" :loading="reviewLoading" @click="submitReview">提交审核</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="showViewDialog" title="科研项目详情" width="900px">
      <div v-if="viewData" class="view-content">
        <el-form label-width="120px" class="view-form">
          <el-form-item label="项目名称">
            <el-input v-model="viewData.name" readonly />
          </el-form-item>

          <el-form-item label="项目编号">
            <el-input v-model="viewData.project_number" readonly />
          </el-form-item>

          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="项目类型">
                <el-input v-model="viewData.project_type" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="学科分类">
                <el-input v-model="viewData.subject_category" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目级别">
                <el-input v-model="viewData.level" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="来源单位">
                <el-input v-model="viewData.source_unit" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="负责人">
                <el-input v-model="viewData.leader_name" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="经费总额">
                <el-input v-model="viewData.total_funding" readonly>
                  <template #suffix>万元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="经费来源">
                <el-input v-model="viewData.funding_source" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="到账情况">
                <el-input v-model="viewData.funding_status" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="项目状态">
            <el-tag :type="getStatusTagType(viewData.status)">{{ viewData.status }}</el-tag>
          </el-form-item>

          <!-- 审核意见（如果存在） -->
          <el-form-item label="审核意见" v-if="viewData.review_opinion">
            <el-input v-model="viewData.review_opinion" type="textarea" :rows="3" readonly />
          </el-form-item>

          <!-- 结题审核意见（如果存在） -->
          <el-form-item label="结题审核意见" v-if="viewData.finish_review_opinion">
            <el-input v-model="viewData.finish_review_opinion" type="textarea" :rows="3" readonly />
          </el-form-item>

          <!-- 项目成员 -->
          <el-form-item label="项目成员" v-if="viewData.members && viewData.members.length">
            <el-table :data="viewData.members" border size="small">
              <el-table-column prop="name" label="姓名" width="100" />
              <el-table-column prop="staffNo" label="工号" width="120" />
              <el-table-column prop="department" label="部门" width="120" />
              <el-table-column prop="role" label="角色" width="100" />
              <el-table-column prop="responsibility" label="职责" show-overflow-tooltip />
            </el-table>
          </el-form-item>

          <!-- 经费详情 -->
          <el-form-item label="经费详情" v-if="viewData.fundings && viewData.fundings.length">
            <el-table :data="viewData.fundings" border size="small">
              <el-table-column prop="amount" label="金额(万元)" width="120" />
              <el-table-column prop="source" label="来源" width="120" />
              <el-table-column prop="purpose" label="用途" show-overflow-tooltip />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === '已到账' ? 'success' : (row.status === '部分到账' ? 'warning' : 'info')" size="small">
                    {{ row.status }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <!-- 附件列表 -->
          <el-form-item label="项目附件" v-if="viewData.attachments && viewData.attachments.length">
            <el-table :data="viewData.attachments" border size="small">
              <el-table-column prop="fileName" label="文件名" />
              <el-table-column prop="uploadedAt" label="上传时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.uploadedAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ row }">
                  <el-button type="text" @click="downloadFile(row)">下载</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="showViewDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getPendingReviewResearchProjects, getResearchProjectById, reviewResearchProject, downloadResearchAttachment } from '@/api/researchProject'

const loading = ref(false)
const reviewLoading = ref(false)
const filterStatus = ref('')
const filterType = ref('')
const filterLevel = ref('')
const projects = ref([])

// 审核相关
const showReviewDialog = ref(false)
const showViewDialog = ref(false)
const reviewProject = ref(null)
const viewData = ref(null)

const reviewForm = reactive({
  status: '',
  opinion: ''
})

// 获取待审核项目
const fetchProjects = async () => {
  try {
    loading.value = true
    
    let projectList = []
    const response = await getPendingReviewResearchProjects()
    projectList = Array.isArray(response) ? response : (response?.data || [])
    
    // 按状态筛选
    let filteredProjects = projectList
    if (filterStatus.value) {
      filteredProjects = filteredProjects.filter(p => p.status === filterStatus.value)
    }
    if (filterType.value) {
      filteredProjects = filteredProjects.filter(p => p.projectType === filterType.value)
    }
    if (filterLevel.value) {
      filteredProjects = filteredProjects.filter(p => p.level === filterLevel.value)
    }
    
    projects.value = filteredProjects
  } catch (e) {
    console.error(e)
    ElMessage.error('获取项目列表失败')
    projects.value = []
  } finally {
    loading.value = false
  }
}

// 查看项目详情
const handleView = async (project) => {
  try {
    loading.value = true
    const response = await getResearchProjectById(project.id)
    const detail = response?.data || response
    const proj = detail?.project || detail || {}
    
    viewData.value = {
      id: proj.id,
      name: proj.name,
      project_number: proj.projectNumber,
      project_type: proj.projectType,
      subject_category: proj.subjectCategory,
      level: proj.level,
      source_unit: proj.sourceUnit,
      leader_name: detail?.leaderName,
      total_funding: proj.totalFunding,
      funding_source: proj.fundingSource,
      funding_status: proj.fundingStatus,
      status: proj.status,
      members: detail?.members || [],
      fundings: detail?.fundings || [],
      attachments: detail?.attachments || [],
      review_opinion: proj.reviewOpinion,
      finish_review_opinion: proj.finishReviewOpinion
    }
    showViewDialog.value = true
  } catch (e) {
    console.error(e)
    ElMessage.error('获取项目详情失败')
  } finally {
    loading.value = false
  }
}

// 打开审核对话框
const openReview = (row) => {
  reviewProject.value = row
  reviewForm.status = ''
  reviewForm.opinion = ''
  showReviewDialog.value = true
}

// 提交审核
const submitReview = async () => {
  try {
    if (!reviewForm.status || !reviewForm.opinion) {
      ElMessage.warning('请填写完整的审核信息')
      return
    }
    reviewLoading.value = true
    await reviewResearchProject(reviewProject.value.id, {
      status: reviewForm.status,
      opinion: reviewForm.opinion
    })
    ElMessage.success('审核完成')
    showReviewDialog.value = false
    fetchProjects()
  } catch (e) {
    console.error(e)
    ElMessage.error('审核失败')
  } finally {
    reviewLoading.value = false
  }
}

// 下载文件
const downloadFile = async (attachment) => {
  try {
    await downloadResearchAttachment(attachment.id, attachment.fileName)
    ElMessage.success(`开始下载文件: ${attachment.fileName}`)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

const handleFilterChange = () => {
  fetchProjects()
}

const clearFilters = () => {
  filterStatus.value = ''
  filterType.value = ''
  filterLevel.value = ''
  fetchProjects()
}

// 工具函数
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  try {
    return new Date(dateTimeStr).toLocaleString('zh-CN')
  } catch {
    return '-'
  }
}

const getStatusTagType = (status) => {
  const types = {
    '申报中': 'warning',
    '结题审核中': 'info',
    '已立项': 'success',
    '执行中': 'primary',
    '已结题': 'success',
    '已驳回': 'danger'
  }
  return types[status] || 'info'
}

const getProjectTypeTagType = (type) => {
  const types = {
    '纵向': 'primary',
    '横向': 'success', 
    '校级': 'warning'
  }
  return types[type] || 'info'
}

const getLevelTagType = (level) => {
  const types = {
    '国家级': 'danger',
    '省部级': 'warning',
    '市厅级': 'primary',
    '校级': 'info'
  }
  return types[level] || 'info'
}

onMounted(() => {
  fetchProjects()
})
</script>

<style scoped>
.research-review-center {
  max-width: 1400px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}
.page-title {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}
.header-actions {
  display: flex;
  align-items: center;
}
.filter-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
}
.filter-summary {
  margin-left: auto;
  display: flex;
  align-items: center;
}
.review-info {
  margin-bottom: 20px;
}
.view-content {
  max-height: 600px;
  overflow-y: auto;
}
</style>
